<?php
/**
 *
 * @author junsion
 * @url 
 */
defined('IN_IA') or exit('Access Denied');
require_once IA_ROOT.'/addons/junsion_challeng/func.php';
class Junsion_challengModuleWxapp extends WeModuleWxapp {
	
	public function __construct(){
		global $_GPC, $_W;
		
		$post_gsign = $_GPC['gsign'];
		$timestamp = $_GPC['timestamp'];
		$post_data = $_GPC;
		$data = array();
		$game_compatible = 0;
		foreach ($post_data as $k => $v){
			if(!empty($v) && $k!='__entry' && $k!='__state' && $k!='state' && $k!='sign' && $k!='gsign' && $k!='timestamp')
			{
				$data[$k] = htmlspecialchars_decode($v);
			}
			if($k=='do' && $v=='share')$game_compatible = 1;
		}
		ksort($data);
		$string = $this->ToUrlParams($data);
		$string .= "&timestamp={$timestamp}";
		$cfg = pdo_fetch('select settings from '.tablename('uni_account_modules')." where uniacid='{$_W['uniacid']}' and module='junsion_challeng'");
		$cfg = unserialize($cfg['settings']);
		if(!empty($cfg['junsiontoken'])){
			$sign = md5($string.$cfg['junsiontoken']);
			if($sign!=$post_gsign && $game_compatible==0){
				//密钥错误
				die('400500');
			}
		}
		return ;
	}
	
	private function ToUrlParams($post)
	{
		$buff = "";
		foreach ($post as $k => $v)
		{
			if($k != "sign" && $v != "" && !is_array($v)){
				$buff .= $k . "=" . $v . "&";
			}
		}
		$buff = trim($buff, "&");
		return $buff;
	}
	
	public $ANSWER_ARR = array(-2,-1,10,0,1,2,0,0,0,-10,10,-10);
	
	public function doPageOpenid(){
		global $_GPC, $_W;
		$account_api = WeAccount::create();
		$oauth = $account_api->getOauthInfo($_GPC['code']);
		if($oauth['openid']){
			$s = pdo_fetch('select session_key from ' . tablename($this->modulename.'_session') . " where openid = '{$oauth['openid']}'");
			if(empty($s)) 
				pdo_insert($this->modulename.'_session',array('openid'=>$oauth['openid'],'session_key'=>$oauth['session_key']));
			else 
				pdo_update($this->modulename.'_session',array('session_key'=>$oauth['session_key']),array('openid'=>$oauth['openid']));
		}
		echo $oauth['openid'];
	}
	public function doPageUnionid(){
		global $_GPC, $_W;
		$account_api = WeAccount::create();
		$_SESSION['session_key'] = pdo_fetchcolumn('select session_key from ' . tablename($this->modulename.'_session') . " where openid = '{$_GPC['openid']}'");
		$encrypt_data = $_GPC['encryptedData'];
		$iv = $_GPC['iv'];
		$userinfo = $account_api->pkcs7Encode($encrypt_data, $iv);
		if ($userinfo['unionId']){
			$uniacid = file_get_contents(IA_ROOT."/addons/junsion_challeng/preuniacid{$_W['uniacid']}");
			if ($uniacid > 0){
				$m = get('select id,propenid from '.tb('mem')." where unionid='{$userinfo['unionId']}' and weid='{$_W['uniacid']}'");
				if ($m['id']){
					if($m['propenid'] != $_GPC['openid']){
						$mm = get('select id from '.tb('mem')." where propenid='{$_GPC['openid']}'");
						if ($mm['id']){
							del('mem',array('id'=>$mm['id']));
						}
						update('mem',array('propenid'=>$_GPC['openid']),array('id'=>$m['id']));
						die('1');
					}
				}else pdo_update($this->modulename.'_mem',array('unionid'=>$userinfo['unionId']),array('propenid'=>$_GPC['openid'],'weid'=>$_W['uniacid']));
			}else pdo_update($this->modulename.'_mem',array('unionid'=>$userinfo['unionId']),array('propenid'=>$_GPC['openid'],'weid'=>$_W['uniacid']));
		}
	}
	
	public function doPageMsg(){
		global $_GPC, $_W;
		echo $this->sitefunc('api');
	}
	
	//购买次数
	public function doPageCreateOrder(){
		global $_GPC, $_W;
		echo $this->sitefunc('CreateOrder');
	}
	public function doPageCheckReward(){
		echo $this->sitefunc('CheckReward');
	}
	public function doPageCheckOrder(){
		echo $this->sitefunc('CheckOrder');
	}
	
	public function doPagePlay(){
		global $_GPC, $_W;
		$_W['uniacid'] = $_W['weid'];
		$openid = $_GPC['openid'];
		$arr = array();
		$cfg = $this->module['config'];
		$game = empty($_GPC['game'])?0:$_GPC['game'];
		$mem = $this->checkInfo($openid,$game,$cfg);
		if($game==1){
			$times = rand($cfg['game1']['min_time'],$cfg['game1']['max_time']);
			if(empty($cfg['game1']['min_time'])){
				$times = $cfg['game1']['times'] * 10;
			}
			$max_num = empty($cfg['game1']['maxNum'])?49:$cfg['game1']['maxNum'];
			$min_time = $cfg['game1']['min_time'];
			$max_time = $cfg['game1']['max_time'];
			$arr['sec_game'] = $cfg['game1']['times'];
			$arr['g_time'] = toimage($cfg['face']['g_time']);
		}else{
			$times = rand($cfg['game']['min_time'],$cfg['game']['max_time']);
			$max_num = empty($cfg['game']['maxNum'])?500:$cfg['game']['maxNum'];
			$min_time = $cfg['game']['min_time'];
			$max_time = $cfg['game']['max_time'];
			$arr['change_time'] = $cfg['game']['change_time'];
		}
		if(empty($times)) $times = 10;
		$arr['suctxt'] = $cfg['font']['suctxt'];
		$arr['failtxt'] = $cfg['font']['failtxt'];
		$arr['min_time'] = $min_time;
		$arr['max_time'] = $max_time;
		$arr['express_fee'] = $cfg['base']['express_fee'];
		$arr['maxNum'] = $max_num;
		$arr['resetTime'] = $times;
		$arr['mid'] = $mem['id'];
		if($game==1 || !empty($cfg['isnew'])){
			pdo_query('update '.tablename($this->modulename."_mem")." set challeng_num = challeng_num-1,join_num=join_num+1 where id='{$mem['id']}'");
 		}
 		//生成随机字符串
 		$rand_token = random(10);
 		update('mem',array('gametoken'=>$rand_token),array('id'=>$mem['id']));
 		$arr['gametoken'] = $rand_token;
 		$redis  = $cfg['redis'];
 		if($redis['switch']){
 			$this->delRedisMemLogList($redis, $mem['id']);
 		}
 		else{
 			$path = IA_ROOT.'/addons/junsion_challeng/qrcode/val_'.$mem['id'];
 			if(file_exists($path)){
 				unlink(IA_ROOT.'/addons/junsion_challeng/qrcode/val_'.$mem['id']);
 			}
 		}
		die(json_encode($arr));
	}
	
	public function checkInfo($openid,$game,$cfg=''){
		global $_W;
		$mem = $this->getMem($openid);
		if($mem['status']==1){
			$arr = array(
					'code' => 0,
					'msg' => '您已被拉入黑名单，无法参与'
			);
			die(json_encode($arr));
		}
		if($mem['challeng_num']<=0){
			$arr = array(
					'code' => 2,
					'msg' => '挑战次数不足，无法挑战'
			);
			die(json_encode($arr));
		}
		if(empty($cfg)) $cfg = $this->module['config'];
		$game_status = $cfg['game_status'];
		if(empty($game_status['game'.$game])){
			$arr = array(
					'code' => 0,
					'msg' => '系统未开启该游戏'
			);
			die(json_encode($arr));
		}
		return $mem;
	}
	
	public function getRandAnswers($answer){
		global $_W;
		$rand_txts = randGetTxts();
		$rand_txts = array_merge($rand_txts,$answer);
		$rand_txts = array_unique($rand_txts);
		$rand_total = count($rand_txts);
		$other_num = $rand_total - 32;
		for ($i=0;$i<$other_num;$i++){
			unset($rand_txts[$i]);
		}
		shuffle($rand_txts);
		return $rand_txts;
	}
	
	public function strencode($string,$key,$str_time) {
		$string = base64_encode(urlencode($string));
		$key = md5($key.$str_time);
		$len = strlen($key);
		$code = '';
		for ($i = 0; $i < strlen($string); $i++) {
			$k = $i % $len;
			$code .= $string [$i] ^ $key [$k];
		}
		return base64_encode($code);
	}
	
	public function doPageZplay(){
		global $_GPC, $_W;
		$_W['uniacid'] = $_W['weid'];
		$openid = $_GPC['openid'];
		$game = empty($_GPC['game'])?0:$_GPC['game'];
		$cfg = $this->module['config'];
		$mem = $this->checkInfo($openid,$game,$cfg);
		$game = $cfg['game9'];
		if($game['total']<=0){
			$arr = array(
					'code' => 0,
					'msg' => '系统错误，请联系管理员'
			);
			die(json_encode($arr));
		}
		unset($mem['gametoken']);
		$pics = array(
				'bridge' => toimage($game['bridge']),
				'platform' => toimage($game['platform']),
				'g_bg' => toimage($game['g_bg']),
				'monkey' => toimage($game['monkey']),
				'monkey1' => toimage($game['monkey1']),
				
		);
		$arr = array();
		$arr['mem'] = $mem;
		$arr['pics'] = $pics;
		$arr['down'] = $game['down'];
		$arr['total'] = $game['total'];
		$arr['times'] = array($game['firsttime'],$game['secondtime'],$game['thirdtime']);
		$arr['g_nums'] = array($game['firstnum'],$game['secondnum'],$game['thirdnum']);
		$rand_token = random(10);
		$arr['gametoken'] = $rand_token;
		$arr['game_bg'] = toimage($cfg['face']['game_bg']);
		pdo_query('update '.tablename($this->modulename."_mem")." set gametoken='{$rand_token}',challeng_num = challeng_num-1,join_num=join_num+1 where id='{$mem['id']}'");
		die(json_encode($arr));
	}
	
	public function doPageQplay(){
		global $_GPC, $_W;
		$_W['uniacid'] = $_W['weid'];
		$openid = $_GPC['openid'];
		$game = empty($_GPC['game'])?0:$_GPC['game'];
		$cfg = $this->module['config'];
		$mem = $this->checkInfo($openid,$game,$cfg);
		$game = $cfg['game8'];
		if($game['total']<=0){
			$arr = array(
					'code' => 0,
					'msg' => '系统错误，请联系管理员'
			);
			die(json_encode($arr));
		}
		unset($mem['gametoken']);
		$arr = array();
		$arr['mem'] = $mem;
		$arr['down'] = $game['down'];
		$arr['total'] = $game['total'];
		$arr['times'] = array($game['firsttime'],$game['secondtime'],$game['thirdtime']);
		$arr['g_nums'] = array($game['firstnum'],$game['secondnum'],$game['thirdnum']);
		$rand_token = random(10);
		$arr['gametoken'] = $rand_token;
		$arr['game_bg'] = toimage($cfg['face']['game_bg']);
		pdo_query('update '.tablename($this->modulename."_mem")." set gametoken='{$rand_token}',challeng_num = challeng_num-1,join_num=join_num+1 where id='{$mem['id']}'");
		die(json_encode($arr));
	}
	
	public function doPageYplay(){
		global $_GPC, $_W;
		$_W['uniacid'] = $_W['weid'];
		$openid = $_GPC['openid'];
		$game = empty($_GPC['game'])?0:$_GPC['game'];
		$cfg = $this->module['config'];
		$mem = $this->checkInfo($openid,$game,$cfg);
		$game = $cfg['game7'];
		if($game['total']<=0){
			$arr = array(
					'code' => 0,
					'msg' => '系统错误，请联系管理员'
			);
			die(json_encode($arr));
		}
		unset($mem['gametoken']);
		$arr = array();
		$arr['mem'] = $mem;
		$arr['down'] = $game['down'];
		$arr['total'] = $game['total'];
		$arr['total_time'] = $game['total_time'];
		$arr['times'] = array($game['firsttime'],$game['secondtime'],$game['thirdtime']);
		$arr['g_nums'] = array($game['firstnum'],$game['secondnum'],$game['thirdnum']);
		$arr['g_color'] = array($game['firstcolor'],$game['secondcolor'],$game['thirdcolor']);
		$rand_token = random(10);
		$arr['gametoken'] = $rand_token;
		$arr['game_bg'] = toimage($cfg['face']['game_bg']);
		pdo_query('update '.tablename($this->modulename."_mem")." set gametoken='{$rand_token}',challeng_num = challeng_num-1,join_num=join_num+1 where id='{$mem['id']}'");
		die(json_encode($arr));
	}
	
	public function doPageCplay(){
		global $_GPC, $_W;
		$_W['uniacid'] = $_W['weid'];
		$openid = $_GPC['openid'];
		$game = empty($_GPC['game'])?0:$_GPC['game'];
		$cfg = $this->module['config'];
		$mem = $this->checkInfo($openid,$game,$cfg);
		$game = $cfg['game6'];
		if($game['total']<=0){
			$arr = array(
					'code' => 0,
					'msg' => '系统错误，请联系管理员'
			);
			die(json_encode($arr));
		}
		$redis  = $cfg['redis'];
		if($redis['switch']){
			$this->delRedisMemProList($redis, $mem['id']);
		}
		else{
			$path = IA_ROOT.'/addons/junsion_challeng/qrcode/pro_'.$mem['id'];
			if(file_exists($path)){
				unlink(IA_ROOT.'/addons/junsion_challeng/qrcode/pro_'.$mem['id']);
			}
		}
		$str_time = TIMESTAMP;
		$problem = $this->getProblem(6, $mem['id'], $str_time, $cfg);
		
		unset($mem['gametoken']);
		$arr = array();
		$arr['str_time'] = $str_time;
		$arr['mem'] = $mem;
		$arr['down'] = $game['down'];
		$arr['total'] = $game['total'];
		$arr['times'] = array($game['firsttime'],$game['secondtime'],$game['thirdtime']);
		$arr['g_nums'] = array($game['firstnum'],$game['secondnum'],$game['thirdnum']);
		$arr['problem'] = $problem;
		$arr['m_bg'] = toimage($cfg['face']['m_bg']);
		$arr['m_play'] = toimage($cfg['face']['m_play']);
		$arr['m_stop'] = toimage($cfg['face']['m_stop']);
		$arr['g_close'] = toimage($cfg['face']['g_close']);
		$arr['g_shoushi'] = toimage($cfg['face']['g_shoushi']);
		$rand_token = random(10);
		$arr['gametoken'] = $rand_token;
		$arr['game_bg'] = toimage($cfg['face']['game_bg']);
		pdo_query('update '.tablename($this->modulename."_mem")." set gametoken='{$rand_token}',challeng_num = challeng_num-1,join_num=join_num+1 where id='{$mem['id']}'");
		die(json_encode($arr));
	}
	
	public function doPageCheckCPlay(){
		global $_GPC, $_W;
		$_W['uniacid'] = $_W['weid'];
		$str_time = $_GPC['str_time'];
		$mid = intval($_GPC['mid']);
		$game = $_GPC['game'];
		$cfg = $this->module['config'];
		if($game!=6){
			$arr = array(
					'code' => 0,
					'msg' => '游戏模式错误，请刷新重试'
			);
			die(json_encode($arr));
		}
		$problem = $this->getProblem(6, $mid, $str_time, $cfg);
		if(!empty($problem)){
			$arr = array(
					'code' => 1,
					'problem' => $problem,
			);
		}
		else{
			$arr = array(
					'code' => 0,
					'msg' => '获取歌曲失败，请联系管理员',
			);
		}
		die(json_encode($arr));
	}
	
	public function doPageXplay(){
		global $_GPC, $_W;
		$_W['uniacid'] = $_W['weid'];
		$openid = $_GPC['openid'];
		$game = empty($_GPC['game'])?0:$_GPC['game'];
		$cfg = $this->module['config'];
		$mem = $this->checkInfo($openid,$game,$cfg);
		$game = $cfg['game5'];
		if($game['total']<=0){
			$arr = array(
					'code' => 0,
					'msg' => '系统错误，请联系管理员'
			);
			die(json_encode($arr));
		}
		$redis  = $cfg['redis'];
		if($redis['switch']){
			$this->delRedisMemPlayList($redis, $mem['id']);
			$this->delRedisMemLogList($redis, $mem['id']);
			$this->delRedisMemProList($redis, $mem['id']);
		}
		else{
			$path = IA_ROOT.'/addons/junsion_challeng/qrcode/play_'.$mem['id'];
			if(file_exists($path)){
				unlink(IA_ROOT.'/addons/junsion_challeng/qrcode/play_'.$mem['id']);
			}
			$path = IA_ROOT.'/addons/junsion_challeng/qrcode/val_'.$mem['id'];
			if(file_exists($path)){
				unlink(IA_ROOT.'/addons/junsion_challeng/qrcode/val_'.$mem['id']);
			}
			$path = IA_ROOT.'/addons/junsion_challeng/qrcode/pro_'.$mem['id'];
			if(file_exists($path)){
				unlink(IA_ROOT.'/addons/junsion_challeng/qrcode/pro_'.$mem['id']);
			}
		}
		$str_time = TIMESTAMP;
		if($cfg['isnew']){
			$problem = $this->getProblem(5, $mem['id'], $str_time);
			unset($mem['junsiontoken']);
			$arr = array();
			$arr['str_time'] = $str_time;
			$arr['mem'] = $mem;
			$arr['down'] = $game['down'];
			$arr['total'] = $game['total'];
			$arr['times'] = $times;
			$arr['problem'] = $problem;
			$arr['times'] = array($game['firsttime'],$game['secondtime'],$game['thirdtime']);
			$arr['g_nums'] = array($game['firstnum'],$game['secondnum'],$game['thirdnum']);
		}
		else{
			if(!empty($game['firstnum'])){
				$times = $game['firsttime'];
			}
			elseif(!empty($game['secondnum'])){
				$times = $game['secondtime'];
			}
			elseif(!empty($game['thirdnum'])){
				$times = $game['thirdtime'];
			}
			if(empty($game['firstnum']) && empty($game['secondnum']) && empty($game['thirdnum'])){
				$times = 5;
			}
			
			//随机获取一道看图猜词题
			$problem = get('select id,thumb,answer from ' . tb('pic') . " where weid = '{$_W['uniacid']}' and status = 1 order by rand() limit 1");
			if(empty($problem) || empty($problem['thumb']) || empty($problem['answer'])){
				$arr = array(
						'code' => 0,
						'msg' => '系统未设置任何成语，请联系管理员'
				);
				die(json_encode($arr));
			}
			if(empty($game['iurl'])){
				$problem['thumb'] = $_W['siteroot'].'addons/junsion_challeng/public/pics/'.$problem['thumb'];
			}
			else{
				$problem['thumb'] = $game['iurl'].$problem['thumb'];
			}
			$answer = $this->ch2arr($problem['answer']);
			$rand_txts = $this->getRandAnswers($answer);
			$problem['answers'] = $rand_txts;
			$rand_str = '';
			foreach ($rand_txts as $k => $v){
				$rand_str .= $v;
			}
			$check_answer = array();
			foreach ($answer as $k => $v){
				if(!empty($v))$check_answer[]='';
			}
			if(empty($cfg['isnew'])){
				unset($problem['answer']);
			}
			else{
				$str_time = TIMESTAMP;
				$problem['answer'] = $this->strencode($problem['answer'],$cfg['junsiontoken'],$str_time);
			}
			$str_problem[0] = 0;
			$str_problem[1] = $problem['id'];
			$str_problem[2] = $rand_str;
			$str = $str_problem[0].','.$str_problem[1].','.$str_problem[2];
			if($redis['switch']){
				$this->setRedisMemPlayList($redis, $mem['id'], $str);
			}
			else{
				$path = IA_ROOT.'/addons/junsion_challeng/qrcode/play_'.$mem['id'];
				file_put_contents($path, $str);
			}
			$arr = array();
			$arr['str_time'] = $str_time;
			$arr['mem'] = $mem;
			$arr['down'] = $game['down'];
			$arr['total'] = $game['total'];
			$arr['times'] = $times;
			$arr['problem'] = $problem;
			$arr['answer'] = $check_answer;
		}
		$rand_token = random(10);
		$arr['gametoken'] = $rand_token;
		$arr['game_bg'] = toimage($cfg['face']['game_bg']);
		pdo_query('update '.tablename($this->modulename."_mem")." set gametoken='{$rand_token}',challeng_num = challeng_num-1,join_num=join_num+1 where id='{$mem['id']}'");
		die(json_encode($arr));
	}
	
	public function doPageWplay(){
		global $_GPC, $_W;
		$_W['uniacid'] = $_W['weid'];
		$openid = $_GPC['openid'];
		$game = empty($_GPC['game'])?0:$_GPC['game'];
		$cfg = $this->module['config'];
		$mem = $this->checkInfo($openid,$game,$cfg);
		$game = $cfg['game4'];
		if($game['total']<=0){
			$arr = array(
					'code' => 0,
					'msg' => '系统错误，请联系管理员'
			);
			die(json_encode($arr));
		}
		$redis  = $cfg['redis'];
		if($redis['switch']){
			$this->delRedisMemPlayList($redis, $mem['id']);
			$this->delRedisMemLogList($redis, $mem['id']);
			$this->delRedisMemProList($redis, $mem['id']);
		}
		else{
			$path = IA_ROOT.'/addons/junsion_challeng/qrcode/play_'.$mem['id'];
			if(file_exists($path)){
				unlink(IA_ROOT.'/addons/junsion_challeng/qrcode/play_'.$mem['id']);
			}
			$path = IA_ROOT.'/addons/junsion_challeng/qrcode/val_'.$mem['id'];
			if(file_exists($path)){
				unlink(IA_ROOT.'/addons/junsion_challeng/qrcode/val_'.$mem['id']);
			}
			$path = IA_ROOT.'/addons/junsion_challeng/qrcode/pro_'.$mem['id'];
			if(file_exists($path)){
				unlink(IA_ROOT.'/addons/junsion_challeng/qrcode/pro_'.$mem['id']);
			}
		}
		$str_time = TIMESTAMP;
		if($cfg['isnew']){
			$phrase = $this->getProblem(4, $mem['id'], $str_time);
			unset($mem['junsiontoken']);
			$arr = array();
			$arr['str_time'] = $str_time;
			$arr['mem'] = $mem;
			$arr['down'] = $game['down'];
			$arr['total'] = $game['total'];
			$arr['times'] = array($game['firsttime'],$game['secondtime'],$game['thirdtime']);
			$arr['g_nums'] = array($game['firstnum'],$game['secondnum'],$game['thirdnum']);
			$arr['problem'] = $phrase;
		}
		else{
			if(!empty($game['firstnum'])){
				$times = $game['firsttime'];
			}
			elseif(!empty($game['secondnum'])){
				$times = $game['secondtime'];
			}
			elseif(!empty($game['thirdnum'])){
				$times = $game['thirdtime'];
			}
			if(empty($game['firstnum']) && empty($game['secondnum']) && empty($game['thirdnum'])){
				$times = 5;
			}
			//随机获取一道成语
			$phrase = get('select id,phrase from ' . tb('phrase') . " where 1 order by rand() limit 1");
			if(empty($phrase)){
				$arr = array(
						'code' => 0,
						'msg' => '系统未设置任何成语，请联系管理员'
				);
				die(json_encode($arr));
			}
			$str_time = TIMESTAMP;
			$phrase['phrase1'] = $this->strencode($phrase['phrase'], $cfg['junsiontoken'], $str_time);
			$phrase['phrase'] = $this->ch2arr($phrase['phrase']);
			shuffle($phrase['phrase']);
			$str_phrase = $phrase['phrase'];
			$str_phrase[4] = 0;
			$str_phrase[5] = $phrase['id'];
			$str = $str_phrase[0].','.$str_phrase[1].','.$str_phrase[2].','.$str_phrase[3].','.$str_phrase[4].','.$str_phrase[5];
			if($redis['switch']){
				$this->setRedisMemPlayList($redis, $mem['id'], $str);
			}
			else{
				$path = IA_ROOT.'/addons/junsion_challeng/qrcode/play_'.$mem['id'];
				file_put_contents($path, $str);
			}
			
			$arr = array();
			$arr['str_time'] = $str_time;
			$arr['mem'] = $mem;
			$arr['down'] = $game['down'];
			$arr['total'] = $game['total'];
			$arr['times'] = $times;
			$arr['problem'] = $phrase;
		}
		$rand_token = random(10);
		$arr['gametoken'] = $rand_token;
		$arr['game_bg'] = toimage($cfg['face']['game_bg']);
		pdo_query('update '.tablename($this->modulename."_mem")." set gametoken='{$rand_token}',challeng_num = challeng_num-1,join_num=join_num+1 where id='{$mem['id']}'");
		die(json_encode($arr));
	}
	
	public function doPageCheckXPlay(){
		global $_GPC, $_W;
		$_W['uniacid'] = $_W['weid'];
		$game = $_GPC['game'];
		if($game!=5){
			$arr = array(
					'code' => 0,
					'msg' => '游戏模式错误，请刷新重试'
			);
			die(json_encode($arr));
		}
		$cfg = $this->module['config'];
		if($cfg['isnew']){//新版
			$str_time = $_GPC['str_time'];
			$mid = intval($_GPC['mid']);
			$problem = $this->getProblem(5, $mid, $str_time, $cfg);
			if(!empty($problem)){
				$arr = array(
						'code' => 1,
						'problem' => $problem,
				);
			}
			else{
				$arr = array(
						'code' => 0,
						'msg' => '获取看图填词失败，请联系管理员',
				);
			}
			die(json_encode($arr));
		}
		else{
			$num = $_GPC['num'];
			$cur_i = $_GPC['cur_i'];
			$str_time = $_GPC['str_time'];
			$u_answer = htmlspecialchars_decode($_GPC['uanswer']);
			$u_answer = str_replace(',', '', $u_answer);
			$pid = intval($_GPC['pid']);
			$mid = intval($_GPC['mid']);
			if($game!=5){
				$arr = array(
						'code' => 0,
						'msg' => '游戏模式错误，请刷新重试'
				);
				die(json_encode($arr));
			}
			$problem = get('select id,answer from ' . tb('pic') . " where id = '{$pid}'");
			if(empty($problem) || empty($problem['answer'])){
				$arr = array(
						'code' => 0,
						'msg' => '该看图猜词不存在，请稍后重试'
				);
				die(json_encode($arr));
			}
			if(empty($cfg['isnew']))$answer = $this->ch2arr($problem['answer']);
			$game = $cfg['game5'];
			$redis  = $cfg['redis'];
			if($redis['switch']){
				$str_problem = $this->getRedisMemPlayList($redis, $mid);
				$check_num = $this->getRedisMemLogList($redis, $mid);
			}
			else{
				$path = IA_ROOT.'/addons/junsion_challeng/qrcode/play_'.$mid;
				$str_problem = file_get_contents($path);
				$path = IA_ROOT.'/addons/junsion_challeng/qrcode/val_'.$mid;
				$check_num = file_get_contents($path);
			}
			if(empty($check_num))$check_num=0;
			$str_problem = explode(',', $str_problem);
			$answers = $this->ch2arr($str_problem[2]);
			if(empty($cfg['isnew'])){
				if($answers[$num]!=$answer[$cur_i] || $str_problem[0]!=$cur_i){
					//挑战失败
					$this->updateFriendsRank($mid, $check_num, 5);
					$arr = array(
							'code' => 2,
							'msg' => '回答错误',
					);
					die(json_encode($arr));
				}
			}
			else{
				if($u_answer!=$problem['answer']){
					//挑战失败
					$this->updateFriendsRank($mid, $check_num, 5);
					$arr = array(
							'code' => 2,
							'msg' => '回答错误',
					);
					die(json_encode($arr));
				}
			}
			if(empty($cfg['isnew'])){
				$answer_num = count($answer) - 1;
				if(intval($str_problem[0]) <= $answer_num){
					$str_problem[0] = intval($str_problem[0])+1;
					$str = $str_problem[0].','.$str_problem[1].','.$str_problem[2];
					if($redis['switch']){
						$this->setRedisMemPlayList($redis, $mid, $str);
					}
					else{
						$path = IA_ROOT.'/addons/junsion_challeng/qrcode/play_'.$mid;
						file_put_contents($path, $str);
					}
					$arr = array(
							'code' => 3,
							'msg' => '回答正确',
					);
					die(json_encode($arr));
				}
			}
			//下一题
			if(intval($check_num)<$game['total']){
				$check_num = intval($check_num)+1;
				if($redis['switch']){
					$this->setRedisMemLogList($redis, $mid, $check_num);
				}
				else{
					file_put_contents(IA_ROOT.'/addons/junsion_challeng/qrcode/val_'.$mid, $check_num);
				}
				$pids_str = $str_problem[1];
				$pids = str_replace('_', ',', $pids_str);
				$con = " and id not in ( {$pids} ) ";
				$problem = get('select id,thumb,answer from ' . tb('pic') . " where weid = '{$_W['uniacid']}' and status = 1 {$con} order by rand() limit 1");
				if(empty($problem) || empty($problem['thumb']) || empty($problem['answer'])){
					$arr = array(
							'code' => 0,
							'msg' => '系统未设置任何成语，请联系管理员'
					);
					die(json_encode($arr));
				}
				if(empty($game['iurl'])){
					$problem['thumb'] = $_W['siteroot'].'addons/junsion_challeng/public/pics/'.$problem['thumb'];
				}
				else{
					$problem['thumb'] = $game['iurl'].$problem['thumb'];
				}
				$answer = $this->ch2arr($problem['answer']);
				$rand_txts = $this->getRandAnswers($answer);
				$problem['answers'] = $rand_txts;
				$rand_str = '';
				foreach ($rand_txts as $k => $v){
					$rand_str .= $v;
				}
				$check_answer = array();
				foreach ($answer as $k => $v){
					if(!empty($v))$check_answer[]='';
				}
				$problem['answer'] = $this->strencode($problem['answer'],$cfg['junsiontoken'],$str_time);
				$str_problem[0] = 0;
				$str_problem[1] = $pids_str.'_'.$problem['id'];
				$str_problem[2] = $rand_str;
				$str = $str_problem[0].','.$str_problem[1].','.$str_problem[2];
				if($redis['switch']){
					$this->setRedisMemPlayList($redis, $mid, $str);
				}
				else{
					$path = IA_ROOT.'/addons/junsion_challeng/qrcode/play_'.$mid;
					file_put_contents($path, $str);
				}
			}
			if(intval($check_num)<=$game['firstnum']){
				$times = $game['firsttime'];
			}
			elseif(intval($check_num)<=$game['secondnum']){
				$times = $game['secondtime'];
			}
			elseif(intval($check_num)<=$game['thirdnum']){
				$times = $game['thirdtime'];
			}
			if(empty($game['firstnum']) && empty($game['secondnum']) && empty($game['thirdnum'])){
				$times = 5;
			}
			$arr = array(
					'code' => 1,
					'msg' => '回答正确',
					'num' => $check_num,
					'problem' => $problem,
					'answer' => $check_answer,
					'times' => $times,
			);
			die(json_encode($arr));
		}
	}
	
	public function doPageCheckWPlay(){
		global $_GPC, $_W;
		$_W['uniacid'] = $_W['weid'];
		$game = $_GPC['game'];
		if($game!=4 || $num>3){
			$arr = array(
					'code' => 0,
					'msg' => '游戏模式错误，请刷新重试'
			);
			die(json_encode($arr));
		}
		$cfg = $this->module['config'];
		if($cfg['isnew']){//新版
			$str_time = $_GPC['str_time'];
			$mid = intval($_GPC['mid']);
			$problem = $this->getProblem(4, $mid, $str_time, $cfg);
			if(!empty($problem)){
				$arr = array(
						'code' => 1,
						'problem' => $problem,
				);
			}
			else{
				$arr = array(
						'code' => 0,
						'msg' => '获取成语失败，请联系管理员',
				);
			}
			die(json_encode($arr));
		}
		else{
			$num = $_GPC['num'];
			$cur_i = $_GPC['cur_i'];
			$str_time = $_GPC['str_time'];
			$pid = intval($_GPC['pid']);
			$mid = intval($_GPC['mid']);
			$phrase = get('select id,phrase from ' . tb('phrase') . " where id = '{$pid}'");
			if(empty($phrase)){
				$arr = array(
						'code' => 0,
						'msg' => '该成语不存在，请稍后重试'
				);
				die(json_encode($arr));
			}
			$phrase_info = $this->ch2arr($phrase['phrase']);
			$cur_phrase = $phrase_info[$cur_i];
			$game = $cfg['game4'];
			$redis  = $cfg['redis'];
			if($redis['switch']){
				$str_phrase = $this->getRedisMemPlayList($redis, $mid);
				$check_num = $this->getRedisMemLogList($redis, $mid);
			}
			else{
				$path = IA_ROOT.'/addons/junsion_challeng/qrcode/play_'.$mid;
				$str_phrase = file_get_contents($path);
				$path = IA_ROOT.'/addons/junsion_challeng/qrcode/val_'.$mid;
				$check_num = file_get_contents($path);
			}
			if(empty($check_num))$check_num=0;
			$str_phrase = explode(',', $str_phrase);
			if(($str_phrase[$num]!=$cur_phrase || $str_phrase[4]!=$cur_i) && empty($cfg['isnew'])){
				$this->updateFriendsRank($mid, $check_num, 4);
				$arr = array(
						'code' => 2,
						'msg' => '回答错误',
				);
				die(json_encode($arr));
			}
			if(intval($str_phrase[4])!=3 && empty($cfg['isnew'])){
				$str_phrase[4] = intval($str_phrase[4])+1;
				$str = $str_phrase[0].','.$str_phrase[1].','.$str_phrase[2].','.$str_phrase[3].','.$str_phrase[4].','.$str_phrase[5];
				if($redis['switch']){
					$this->setRedisMemPlayList($redis, $mid, $str);
				}
				else{
					$path = IA_ROOT.'/addons/junsion_challeng/qrcode/play_'.$mid;
					file_put_contents($path, $str);
				}
				$arr = array(
						'code' => 3,
						'msg' => '回答正确',
				);
				die(json_encode($arr));
				
			}
			if(intval($check_num)<$game['total']){
				//此题答完，获取下一题
				$check_num = intval($check_num)+1;
				if($redis['switch']){
					$this->setRedisMemLogList($redis, $mid, $check_num);
				}
				else{
					file_put_contents(IA_ROOT.'/addons/junsion_challeng/qrcode/val_'.$mid, $check_num);
				}
				$pids_str = $str_phrase[5];
				$pids = str_replace('_', ',', $pids_str);
				$con = " and id not in ( {$pids} ) ";
				$phrase = get('select id,phrase from ' . tb('phrase') . " where 1 {$con} order by rand() limit 1");
				$phrase['phrase1'] = $this->strencode($phrase['phrase'], $cfg['junsiontoken'], $str_time);
				$phrase['phrase'] = $this->ch2arr($phrase['phrase']);
				shuffle($phrase['phrase']);
				$str_phrase = $phrase['phrase'];
				$str_phrase[4] = 0;
				$str_phrase[5] = $pids_str.'_'.$phrase['id'];
				$str = $str_phrase[0].','.$str_phrase[1].','.$str_phrase[2].','.$str_phrase[3].','.$str_phrase[4].','.$str_phrase[5];
				if($redis['switch']){
					$this->setRedisMemPlayList($redis, $mid, $str);
				}
				else{
					$path = IA_ROOT.'/addons/junsion_challeng/qrcode/play_'.$mid;
					file_put_contents($path, $str);
				}
			}
			if(intval($check_num)<=$game['firstnum']){
				$times = $game['firsttime'];
			}
			elseif(intval($check_num)<=$game['secondnum']){
				$times = $game['secondtime'];
			}
			elseif(intval($check_num)<=$game['thirdnum']){
				$times = $game['thirdtime'];
			}
			if(empty($game['firstnum']) && empty($game['secondnum']) && empty($game['thirdnum'])){
				$times = 5;
			}
			$arr = array(
					'code' => 1,
					'msg' => '回答正确',
					'num' => $check_num,
					'problem' => $phrase,
					'times' => $times,
			);
			die(json_encode($arr));
		}
	}
	
	public function ch2arr($str)
	{
		$length = mb_strlen($str, 'utf-8');
		$array = [];
		for ($i=0; $i<$length; $i++)
			$array[] = mb_substr($str, $i, 1, 'utf-8');
			return $array;
	}
	
	public function doPageFplay(){
		global $_GPC, $_W;
		$_W['uniacid'] = $_W['weid'];
		$openid = $_GPC['openid'];
		$game = empty($_GPC['game'])?0:$_GPC['game'];
		$cfg = $this->module['config'];
		$mem = $this->checkInfo($openid,$game,$cfg);
		$game = $cfg['game3'];
		if($game['total']<=0){
			$arr = array(
					'code' => 0,
					'msg' => '系统错误，请联系管理员'
			);
			die(json_encode($arr));
		}
		$redis  = $cfg['redis'];
		if($redis['switch']){
			$this->delRedisMemPlayList($redis, $mem['id']);
			$this->delRedisMemLogList($redis, $mem['id']);
			$this->delRedisMemProList($redis, $mem['id']);
		}
		else{
			$path = IA_ROOT.'/addons/junsion_challeng/qrcode/play_'.$mem['id'];
			if(file_exists($path)){
				unlink(IA_ROOT.'/addons/junsion_challeng/qrcode/play_'.$mem['id']);
			}
			$path = IA_ROOT.'/addons/junsion_challeng/qrcode/val_'.$mem['id'];
			if(file_exists($path)){
				unlink(IA_ROOT.'/addons/junsion_challeng/qrcode/val_'.$mem['id']);
			}
			$path = IA_ROOT.'/addons/junsion_challeng/qrcode/pro_'.$mem['id'];
			if(file_exists($path)){
				unlink(IA_ROOT.'/addons/junsion_challeng/qrcode/pro_'.$mem['id']);
			}
		}
		if($cfg['isnew']){
			unset($mem['junsiontoken']);
			$arr = array();
			$arr['mem'] = $mem;
			$arr['down'] = $game['down'];
			$arr['total'] = $game['total'];
			$arr['times'] = array($game['firsttime'],$game['secondtime'],$game['thirdtime']);
			$arr['g_nums'] = array($game['firstnum'],$game['secondnum'],$game['thirdnum']);
		}
		else{
			//随机生成题目
			if(!empty($game['firstnum'])){
				$res = $this->createQuestion($mem['id']);
				$times = $game['firsttime'];
			}
			elseif(!empty($game['secondnum'])){
				$res = $this->createQuestion($mem['id'],1);
				$times = $game['secondtime'];
			}
			elseif(!empty($game['thirdnum'])){
				$res = $this->createQuestion($mem['id'],2);
				$times = $game['thirdtime'];
			}
			if(empty($game['firstnum']) && empty($game['secondnum']) && empty($game['thirdnum'])){
				$res = $this->createQuestion($mem['id']);
				$times = 5;
			}
			$arr = array();
			$arr['mem'] = $mem;
			$arr['down'] = $game['down'];
			$arr['total'] = $game['total'];
			$arr['times'] = $times;
			$arr['problem'] = $res;
		}
		//生成随机字符串
		$rand_token = random(10);
		$arr['gametoken'] = $rand_token;
		$arr['game_bg'] = toimage($cfg['face']['game_bg']);
		pdo_query('update '.tablename($this->modulename."_mem")." set gametoken='{$rand_token}',challeng_num = challeng_num-1,join_num=join_num+1 where id='{$mem['id']}'");
		die(json_encode($arr));
	}	
	
	public function doPageCheckFPlay(){
		global $_GPC, $_W;
		$_W['uniacid'] = $_W['weid'];
		$num = $_GPC['num'];
		$mid = intval($_GPC['mid']);
		$game = $_GPC['game'];
		$cfg = $this->module['config'];
		if($game!=3){
			$arr = array(
					'code' => 0,
					'msg' => '游戏模式错误，请刷新重试'
			);
			die(json_encode($arr));
		}
		$game = $cfg['game3'];
		$redis  = $cfg['redis'];
		if($redis['switch']){
			$right_answer = $this->getRedisMemPlayList($redis, $mid);
			$check_num = $this->getRedisMemLogList($redis, $mid);
		}
		else{
			$right_answer = file_get_contents(IA_ROOT.'/addons/junsion_challeng/qrcode/play_'.$mid);//答案正确与否
			$check_num = file_get_contents(IA_ROOT.'/addons/junsion_challeng/qrcode/val_'.$mid);
		}
		if(empty($check_num))$check_num=0;
		if(($num==1 && $right_answer==1) || ($num==0 && $right_answer==2)){
			$check_num = intval($check_num)+1;
			if($redis['switch']){
				$this->setRedisMemLogList($redis, $mid, $check_num);
			}
			else{
				file_put_contents(IA_ROOT.'/addons/junsion_challeng/qrcode/val_'.$mid, $check_num);
			}
			$times = 5;
			if($check_num<$game['total']){
				//出题
				if($check_num <= $game['firstnum']){
					$res = $this->createQuestion($mid);
					$times = $game['firsttime'];
				}
				elseif ($check_num > $game['firstnum'] && $check_num <= $game['secondnum']){
					$res = $this->createQuestion($mid,1);
					$times = $game['secondtime'];
				}
				elseif ($check_num > $game['secondnum'] && $check_num <= $game['thirdnum']){
					$res = $this->createQuestion($mid,2);
					$times = $game['thirdtime'];
				}
				else{
					$res = $this->createQuestion($mid);
					$times = 5;
				}
			}
			$arr = array(
					'code' => 1,
					'msg' => '回答正确',
					'num' => $check_num,
					'problem' => $res,
					'times' => $times
			);
		}
		else{
			//更新群内排名
			$this->updateFriendsRank($mid, $check_num, 3);
			$arr = array(
					'code' => 2,
					'msg' => '回答错误',
			);
		}
		die(json_encode($arr));
	}
	
	/**
	 * 
	 * @param unknown $type 0简单 1中等 2困难
	 */
	public function createQuestion($mid,$type=0){
		global $_W;
		$answer = $this->ANSWER_ARR;
		$rand_num = array_rand($answer,1);
		if($type==1){
			$rand_num1 = rand(10,99);
			$rand_num2 = rand(10,99);
		}
		elseif($type==2){
			$rand_num1 = rand(100,999);
			$rand_num2 = rand(100,999);
		}
		else{
			$rand_num1 = rand(1,9);
			$rand_num2 = rand(1,9);
		}
		$get_type = rand(0,1);//0加 1减
		if($get_type==1){
			$right_num = $rand_num1 - $rand_num2 + $answer[$rand_num];
		}
		else{
			$right_num = $rand_num1 + $rand_num2 + $answer[$rand_num];
		}
		$arr = array($rand_num1,$rand_num2,$right_num,$get_type);
		if($answer[$rand_num] == 0){
			$num = 1;
		}
		else{
			$num = 2;
		}
		$cfg = $this->module['config'];
		$redis  = $cfg['redis'];
		if($redis['switch']){
			$this->setRedisMemPlayList($redis, $mid, $num);
		}
		else{
			file_put_contents(IA_ROOT.'/addons/junsion_challeng/qrcode/play_'.$mid, $num);
		}
		return $arr;
	}
	
	public function getProblem($g_type,$mid,$str_time,$cfg='',$num=0){
		global $_W;
		if(empty($cfg)) $cfg = $this->module['config'];
		//获取已经存在的题目id
		$redis = $cfg['redis'];
		if($redis['switch']){
			$pids = $this->getRedisMemProList($redis, $mid);
		}
		else {
			$path = IA_ROOT.'/addons/junsion_challeng/qrcode/pro_'.$mid;
			$pids = file_get_contents($path);
		}
		$con = '';
		if(!empty($pids)){
			$con .= ' and id not in ('.str_replace('_', ',', $pids).') ';
		}
		//获取对应游戏的设置
		$game = $cfg['game'.$g_type];
		if($g_type == 6){
			$problem = getall('select id,music,answer from ' . tb('music') . " where 1=1 {$con} order by rand() limit 10");
			if(empty($problem)) return ;
			foreach ($problem as $k => &$v){
				if(!empty($pids)) $pids .= '_';
				$pids .= $v['id'];
				if(empty($game['iurl'])){
					$v['music'] = $_W['siteroot'].'addons/junsion_challeng/public/muscis/'.$v['music'];
				}
				else{
					$v['music'] = $game['iurl'].$v['music'];
				}
				$answer = $this->ch2arr($v['answer']);
				$rand_txts = $this->getRandAnswers($answer);
				$v['answers'] = $rand_txts;
				$rand_str = '';
				foreach ($rand_txts as $kk => $vv){
					$rand_str .= $vv;
				}
				$check_answer = array();
				foreach ($answer as $kk => $vv){
					if(!empty($vv))$check_answer[]='';
				}
				$v['answer'] = $this->strencode($v['answer'],$cfg['junsiontoken'],$str_time);
				$v['check_answer'] = $check_answer;
			}
		}
		elseif($g_type == 5){
			$problem = getall('select id,thumb,answer from ' . tb('pic') . " where weid = '{$_W['uniacid']}' {$con} order by rand() limit 10");
			if(empty($problem)) return ;
			foreach ($problem as $k => &$v){
				if(!empty($pids)) $pids .= '_';
				$pids .= $v['id'];
				if(empty($game['iurl'])){
					$v['thumb'] = $_W['siteroot'].'addons/junsion_challeng/public/pics/'.$v['thumb'];
				}
				else{
					$v['thumb'] = $game['iurl'].$v['thumb'];
				}
				$answer = $this->ch2arr($v['answer']);
				$rand_txts = $this->getRandAnswers($answer);
				$v['answers'] = $rand_txts;
				$rand_str = '';
				foreach ($rand_txts as $kk => $vv){
					$rand_str .= $vv;
				}
				$check_answer = array();
				foreach ($answer as $kk => $vv){
					if(!empty($vv))$check_answer[]='';
				}
				$v['answer'] = $this->strencode($v['answer'],$cfg['junsiontoken'],$str_time);
				$v['check_answer'] = $check_answer;
			}
		}
		elseif($g_type == 4){
			$problem = getall('select id,phrase from ' . tb('phrase') . " where 1 {$con} order by rand() limit 10");
			if(empty($problem)) return ;
			foreach ($problem as $k => &$v){
				if(!empty($pids)) $pids .= '_';
				$pids .= $v['id'];
				$v['phrase1'] = $this->strencode($v['phrase'], $cfg['junsiontoken'], $str_time);
				$v['phrase'] = $this->ch2arr($v['phrase']);
				shuffle($v['phrase']);
			}
		}
		elseif($g_type == 2){
			$limit = '';
			if ($game['second']<=$num){//困难
				$con .= ' and level = 2 ';
				$p_num = $game['third'] - $game['second'];
				$limit = ' limit '.$p_num;
			}elseif($game['first']<=$num){//中等
				$con .= ' and level = 1 ';
				$p_num = $game['second'] - $game['first'];
				$limit = ' limit '.$p_num;
			}
			else{//简单
				$con .= ' and level = 0 ';
				$limit = ' limit '.$game['first'];
			}
			$problem = getall('select id,title,answers,answer from ' . tb('problem') . " where weid = '{$_W['uniacid']}' and status = 1 {$con} order by rand() {$limit}");
			if(empty($problem)) return ;
			foreach ($problem as $k => &$v){
				if(!empty($pids)) $pids .= '_';
				$pids .= $v['id'];
				$p_answer = unserialize($v['answers']);
				foreach ($p_answer as $kk => $vv){
					$p_answer[$kk]['status'] = 'default';
				}
				$v['answers'] = $p_answer;
				$v['answer'] = $this->strencode($v['answer'], $cfg['junsiontoken'], $str_time);
			}
		}
		if($redis['switch']){
			$this->setRedisMemProList($redis, $mid, $pids);
		}
		else {
			file_put_contents(IA_ROOT.'/addons/junsion_challeng/qrcode/pro_'.$mid, $pids);
		}
		return $problem;
	}
	
	public function doPageTplay(){
		global $_GPC, $_W;
		$_W['uniacid'] = $_W['weid'];
		$openid = $_GPC['openid'];
		$game = empty($_GPC['game'])?0:$_GPC['game'];
		$cfg = $this->module['config'];
		$mem = $this->checkInfo($openid,$game,$cfg);
		$game = $cfg['game2'];
		if($game['problem']<=0 || $game['times']<=0){
			$arr = array(
					'code' => 0,
					'msg' => '系统错误，请联系管理员'
			);
			die(json_encode($arr));
		}
		$redis  = $cfg['redis'];
		if($redis['switch']){
			$this->delRedisMemLogList($redis, $mem['id']);
			$this->delRedisMemPlayList($redis, $mem['id']);
			$this->delRedisMemProList($redis, $mem['id']);
		}
		else{
			$path = IA_ROOT.'/addons/junsion_challeng/qrcode/val_'.$mem['id'];
			if(file_exists($path)){
				unlink(IA_ROOT.'/addons/junsion_challeng/qrcode/val_'.$mem['id']);
			}
			$path = IA_ROOT.'/addons/junsion_challeng/qrcode/play_'.$mem['id'];
			if(file_exists($path)){
				unlink(IA_ROOT.'/addons/junsion_challeng/qrcode/play_'.$mem['id']);
			}
			$path = IA_ROOT.'/addons/junsion_challeng/qrcode/pro_'.$mem['id'];
			if(file_exists($path)){
				unlink(IA_ROOT.'/addons/junsion_challeng/qrcode/pro_'.$mem['id']);
			}
		}
		$str_time = TIMESTAMP;
		if($cfg['isnew']){
			$first_problem = $this->getProblem(2, $mem['id'], $str_time);
			unset($mem['junsiontoken']);
			$arr = array();
			$arr['mem'] = $mem;
			$arr['str_time'] = $str_time;
			$arr['problem'] = $first_problem;
			$arr['times'] = $game['times'];
			$arr['g_nums'] = array($game['first'],$game['second'],$game['third']);
			$arr['down'] = $game['down'];
			$arr['problem_num'] = $game['problem'];
			$arr['g_over'] = toimage($cfg['face']['g_over']);
			$arr['g_close'] = toimage($cfg['face']['g_close']);
			$arr['g_shoushi'] = toimage($cfg['face']['g_shoushi']);
		}
		else{
			$con = '';
			if(!empty($game['first'])){
				$con .= ' and level = 0 ';
			}
			elseif (empty($game['first']) && !empty($game['second'])){
				$con .= ' and level = 1 ';
			}
			else{
				$con .= ' and level = 2 ';
			}
			$first_problem = get('select id,title,answers from ' . tb('problem') . " where weid = '{$_W['uniacid']}' and status = 1 {$con} order by rand() limit 1");
			if(empty($first_problem)){
				$arr = array(
						'code' => 0,
						'msg' => '系统未设置题库，请联系管理员'
				);
				die(json_encode($arr));
			}
			$p_answer = unserialize($first_problem['answers']);
			foreach ($p_answer as $k => $v){
				$p_answer[$k]['status'] = 'default';
			}
			unset($mem['gametoken']);
			$first_problem['answers'] = $p_answer;
			$arr = array();
			$arr['mem'] = $mem;
			$arr['problem'] = $first_problem;
			$arr['times'] = $game['times'];
			$arr['down'] = $game['down'];
			$arr['problem_num'] = $game['problem'];
			$arr['g_over'] = toimage($cfg['face']['g_over']);
			$arr['g_close'] = toimage($cfg['face']['g_close']);
			$arr['g_shoushi'] = toimage($cfg['face']['g_shoushi']);
			//添加已回答的问题id
			$problem_str = $first_problem['id'];
			if($redis['switch']){
				$this->setRedisMemPlayList($redis, $mem['id'], $problem_str);
			}
			else{
				file_put_contents(IA_ROOT.'/addons/junsion_challeng/qrcode/play_'.$mem['id'], $problem_str);
			}
		}
		$rand_token = random(10);
		$arr['gametoken'] = $rand_token;
		$arr['game_bg'] = toimage($cfg['face']['game_bg']);
		//减少会员挑战次数
		pdo_query('update '.tablename($this->modulename."_mem")." set gametoken='{$rand_token}',challeng_num = challeng_num-1,join_num=join_num+1 where id='{$mem['id']}'");
		die(json_encode($arr));
	}
	
	public function doPageResetTime(){
		global $_GPC, $_W;
		$cfg = $this->module['config'];
		$game = $_GPC['game'];
		if($game==1){
			$times = rand($cfg['game1']['min_time'],$cfg['game1']['max_time']);
		}
		else{
			$times = rand($cfg['game']['min_time'],$cfg['game']['max_time']);
		}
		if(empty($times)) $times = 10;
		$arr = array(
				'resetTime' => $times
		);
		die(json_encode($arr));
	}
	
	public function doPageCheckAnswer(){
		global $_GPC, $_W;
		$_W['uniacid'] = $_W['weid'];
		$game = $_GPC['game'];
		$num = $_GPC['num'];
		$cfg = $this->module['config'];
		if($game!=2){
			$arr = array(
					'code' => 0,
					'msg' =>'挑战游戏错误，请重新选游戏'
			);
			die(json_encode($arr));
		}
		if($cfg['isnew']){//新版
			$str_time = $_GPC['str_time'];
			$mid = intval($_GPC['mid']);
			$p_num = intval($_GPC['p_num']) + 1;
			$problem = $this->getProblem(2, $mid, $str_time, $cfg, $p_num);

			if(!empty($problem)){
				$arr = array(
						'code' => 1,
						'problem' => $problem,
				);
			}
			else{
				$arr = array(
						'code' => 0,
						'msg' => '获取题目失败，请联系管理员',
				);
			}
			die(json_encode($arr));
		}
		else{
			$val = $_GPC['num'];
			$pid = $_GPC['pid'];
			$mid = $_GPC['mid'];
			$problem = get('select id,answer,level from ' . tb('problem') . " where id = '{$pid}'");
			if(empty($problem)){
				$arr = array(
						'code' => 0,
						'msg' =>'该问题不存在，请联系管理员'
				);
				die(json_encode($arr));
			}
			$redis  = $cfg['redis'];
			if($redis['switch']){
				$check_num = $this->getRedisMemLogList($redis, $mid);
				$check_problem = $this->getRedisMemPlayList($redis, $mid);
			}
			else{
				$check_num = file_get_contents(IA_ROOT.'/addons/junsion_challeng/qrcode/val_'.$mid);
				$check_problem = file_get_contents(IA_ROOT.'/addons/junsion_challeng/qrcode/play_'.$mid);
			}
			if(empty($check_num))$check_num=0;
			if($problem['answer'] != ($val+1)){
				//更新群内排名
				$this->updateFriendsRank($mid, $check_num, 2);
				if($problem['level']==2){
					$arr = array(
							'code' => 3,
							'msg' =>'答案错误',
					);
				}
				else{
					//回答错误重新分配题目
					$con = '';
					if($check_num <= $game['first']){
						$con .= ' and level = 0 ';
					}
					elseif ($check_num > $game['first'] && $check_num <= $game['second']){
						$con .= ' and level = 1 ';
					}
					else{
						$con .= ' and level = 2 ';
					}
					if(!empty($check_problem)){
						$con .= " and id not in ( $check_problem ) ";
					}
					$first_problem = get('select id,title,answers from ' . tb('problem') . " where weid = '{$_W['uniacid']}' and status = 1 {$con} order by rand() limit 1");
					$p_answer = unserialize($first_problem['answers']);
					foreach ($p_answer as $k => $v){
						$p_answer[$k]['status'] = 'default';
					}
					$first_problem['answers'] = $p_answer;
					$arr = array(
							'code' => 2,
							'msg' =>'答案错误',
							'answer' => $problem['answer'] - 1,
							'problem' => $first_problem,
					);
				}
				die(json_encode($arr));
			}
			$check_num = intval($check_num)+1;
			if($redis['switch']){
				$this->setRedisMemLogList($redis, $mid, $check_num);
			}
			else{
				file_put_contents(IA_ROOT.'/addons/junsion_challeng/qrcode/val_'.$mid, $check_num);
			}
			$con = '';
			if($check_num <= $game['first']){
				$con .= ' and level = 0 ';
			}
			elseif ($check_num > $game['first'] && $check_num <= $game['second']){
				$con .= ' and level = 1 ';
			}
			else{
				$con .= ' and level = 2 ';
			}
			if(!empty($check_problem)){
				$con .= " and id not in ( $check_problem ) ";
			}
			$first_problem = get('select id,title,answers from ' . tb('problem') . " where weid = '{$_W['uniacid']}' and status = 1 {$con} {$problem_con} order by rand() limit 1");
			$p_answer = unserialize($first_problem['answers']);
			foreach ($p_answer as $k => $v){
				$p_answer[$k]['status'] = 'default';
			}
			$first_problem['answers'] = $p_answer;
			
			$check_problem .= ",".$first_problem['id'];
			if($redis['switch']){
				$this->setRedisMemPlayList($redis, $mid, $check_problem);
			}
			else{
				file_put_contents(IA_ROOT.'/addons/junsion_challeng/qrcode/play_'.$mid, $check_problem);
			}
			$arr = array(
					'code' => 1,
					'msg' =>'回答正确',
					'num' => $check_num,
					'problem' => $first_problem,
					
			);
			die(json_encode($arr));
		}
	}
	
	//匹配数字
	public function doPageCheckVal(){
		global $_GPC, $_W;
		$_W['uniacid'] = $_W['weid'];
		$val = $_GPC['num'];
		$mid = $_GPC['mid'];
		$cfg = $this->module['config'];
		$redis  = $cfg['redis'];
		if($redis['switch']){
			$check_num = $this->getRedisMemLogList($redis, $mid);
			if(($val==1 || empty($check_num)) && empty($_GPC['game']) && empty($cfg['isnew'])){
				pdo_query('update '.tablename($this->modulename."_mem")." set challeng_num = challeng_num-1,join_num=join_num+1 where id='{$mid}'");
			}
			if(empty($check_num) && $val!=1){
				$this->delRedisMemLogList($redis, $mid);
				pdo_query('update '.tablename($this->modulename."_mem")." set last_num = '{$check_num}' where id='{$mid}'");
				$this->updateFriendsRank($mid, $val,empty($_GPC['game'])?0:$_GPC['game']);
				die('挑战失败');
			}
			if(intval($check_num) + 1 != $val){
				$this->delRedisMemLogList($redis, $mid);
				pdo_query('update '.tablename($this->modulename."_mem")." set last_num = '{$check_num}' where id='{$mid}'");
				$this->updateFriendsRank($mid, $val,empty($_GPC['game'])?0:$_GPC['game']);
				die('挑战失败');
			}
			$this->setRedisMemLogList($redis, $mid, $val);
		}
		else{
			$check_num = file_get_contents(IA_ROOT.'/addons/junsion_challeng/qrcode/val_'.$mid);
			if(($val==1 || empty($check_num)) && empty($_GPC['game']) && empty($cfg['isnew'])){
				pdo_query('update '.tablename($this->modulename."_mem")." set challeng_num = challeng_num-1,join_num=join_num+1 where id='{$mid}'");
			}
			if(empty($check_num) && $val!=1){
				unlink(IA_ROOT.'/addons/junsion_challeng/qrcode/val');
				pdo_query('update '.tablename($this->modulename."_mem")." set last_num = '{$check_num}' where id='{$mid}'");
				$this->updateFriendsRank($mid, $val,empty($_GPC['game'])?0:$_GPC['game']);
				die('挑战失败');
			}
			if(intval($check_num) + 1 != $val){
				unlink(IA_ROOT.'/addons/junsion_challeng/qrcode/val_'.$mid);
				pdo_query('update '.tablename($this->modulename."_mem")." set last_num = '{$check_num}' where id='{$mid}'");
				$this->updateFriendsRank($mid, $val,empty($_GPC['game'])?0:$_GPC['game']);
				die('挑战失败');
			}
			
			file_put_contents(IA_ROOT.'/addons/junsion_challeng/qrcode/val_'.$mid, $val);
			
		}
		die('1');
	}
	
	public function setRedisMemPlayList($redis,$mid,$num,$r=''){
		if(!$r){
			$r = new Redis();
			$r->connect(trim($redis['ip']),trim($redis['port']));
			if(trim($redis['passwd']) && $r->auth(trim($redis['passwd']))==false){
				die();
			}
			$r->set('mem_play_list'.$mid,$num);
		}
	}
	public function getRedisMemPlayList($redis,$mid,$r=''){
		if(!$r){
			$r = new Redis();
			$r->connect(trim($redis['ip']),trim($redis['port']));
			if(trim($redis['passwd']) && $r->auth(trim($redis['passwd']))==false){
				die();
			}
			return $r->get('mem_play_list'.$mid);
		}
	}
	public function delRedisMemPlayList($redis,$mid,$r=''){
		if(!$r){
			$r = new Redis();
			$r->connect(trim($redis['ip']),trim($redis['port']));
			if(trim($redis['passwd']) && $r->auth(trim($redis['passwd']))==false){
				die();
			}
			$r->del('mem_play_list'.$mid);
		}
	}
	public function setRedisMemProList($redis,$mid,$str,$r=''){
		if(!$r){
			$r = new Redis();
			$r->connect(trim($redis['ip']),trim($redis['port']));
			if(trim($redis['passwd']) && $r->auth(trim($redis['passwd']))==false){
				die();
			}
			$r->set('mem_pro_list'.$mid,$str);
		}
	}
	public function getRedisMemProList($redis,$mid,$r=''){
		if(!$r){
			$r = new Redis();
			$r->connect(trim($redis['ip']),trim($redis['port']));
			if(trim($redis['passwd']) && $r->auth(trim($redis['passwd']))==false){
				die();
			}
			return $r->get('mem_pro_list'.$mid);
		}
	}
	public function delRedisMemProList($redis,$mid,$r=''){
		if(!$r){
			$r = new Redis();
			$r->connect(trim($redis['ip']),trim($redis['port']));
			if(trim($redis['passwd']) && $r->auth(trim($redis['passwd']))==false){
				die();
			}
			$r->del('mem_pro_list'.$mid);
		}
	}
	
	public function setRedisMemLogList($redis,$mid,$num=1,$r=''){
		if(!$r){
			$r = new Redis();
			$r->connect(trim($redis['ip']),trim($redis['port']));
			if(trim($redis['passwd']) && $r->auth(trim($redis['passwd']))==false){
				die();
			}
			$r->set('mem_log_list'.$mid,$num);
		}
	}
	public function getRedisMemLogList($redis,$mid,$r=''){
		if(!$r){
			$r = new Redis();
			$r->connect(trim($redis['ip']),trim($redis['port']));
			if(trim($redis['passwd']) && $r->auth(trim($redis['passwd']))==false){
				die();
			}
			return $r->get('mem_log_list'.$mid);
		}
	}
	public function delRedisMemLogList($redis,$mid,$r=''){
		if(!$r){
			$r = new Redis();
			$r->connect(trim($redis['ip']),trim($redis['port']));
			if(trim($redis['passwd']) && $r->auth(trim($redis['passwd']))==false){
				die();
			}
			$r->del('mem_log_list'.$mid);
		}
	}
	
	//中奖
	public function doPageGetReward(){
		global $_GPC, $_W;
		$_W['uniacid'] = $_W['weid'];
		$openid = $_GPC['openid'];
		$gametoken = $_GPC['gametoken'];
		$mem = $this->getMem($openid);
		if($mem['status']==1){
			$arr = array(
					'code' => 0,
					'msg' => '您已被拉入黑名单，无法获取奖品'
			);
			die(json_encode($arr));
		}
		$mid = $mem['id'];
		//检测是否真的中奖---TODO
		$cfg = $this->module['config'];
		if($mem['gametoken']!=$gametoken && $cfg['isnew']==1){
			$arr = array(
					'code' => 0,
					'msg' => '获奖渠道错误，无法领奖'
			);
			die(json_encode($arr));
		}
		$redis = $cfg['redis'];
		if($redis['switch']){
			$check_num = $this->getRedisMemLogList($redis, $mid);
		}
		else{
			$check_num = file_get_contents(IA_ROOT.'/addons/junsion_challeng/qrcode/val_'.$mid);
		}
		
		$val = $_GPC['num'];
		$game = $_GPC['game'];
		if($game==1){
			$title = '挑战注意力';
			$max_num = $cfg['game1']['maxNum'];
		}
		elseif ($game==2){
			$title = '挑战知识';
			$max_num = $cfg['game2']['problem'];
		}
		elseif ($game==3){
			$title = '加减大师';
			$max_num = $cfg['game3']['total'];
		}
		elseif ($game==4){
			$title = '成语填填看';
			$max_num = $cfg['game4']['total'];
		}
		elseif ($game==5){
			$title = '看图填词';
			$max_num = $cfg['game5']['total'];
		}
		elseif ($game==6){
			$title = '猜歌达人';
			$max_num = $cfg['game6']['total'];
		}
		elseif ($game==7){
			$title = '挑战眼力';
			$max_num = $cfg['game7']['total'];
		}
		elseif ($game==8){
			$title = '多彩青蛙';
			$max_num = $cfg['game8']['total'];
		}
		elseif ($game==9){
			$title = '猴子过桥';
			$max_num = $cfg['game9']['total'];
		}
		else{
			$title = '挑战智力';
			$max_num = $cfg['game']['maxNum'];
		}
		if(($check_num!=$val || $max_num!=$val || $max_num!=$check_num) && empty($cfg['isnew'])){
			if($redis['switch']){
				$this->delRedisMemLogList($redis, $mid);
			}
			else{
				$path = IA_ROOT.'/addons/junsion_challeng/qrcode/val_'.$mid;
				if(file_exists($path)){
					unlink($path);
				}
			}
			$arr = array(
					'code' => 0,
					'msg' => '挑战不成功，无法领取奖励'
			);
			die(json_encode($arr));
		}
		$data = array(
				'weid' => $_W['uniacid'],
				'mid' => $mem['id'],
				'type' => $game,
				'createtime' => TIMESTAMP
		);
		//是否设置默认奖品
		$gift = get('select id,price,title from ' . tb('gift') . " where weid='{$_W['uniacid']}' and isdefault =1 limit 1");
		if(!empty($gift)) $data['gid'] = $gift['id'];
		pdo_insert($this->modulename.'_reward',$data);
		$newid = pdo_insertid();
		if($newid>0){
			$this->updateFriendsRank($mid, $max_num,$game);
			if($redis['switch']){
				$this->delRedisMemLogList($redis, $mid);
			}else{
				$path = IA_ROOT.'/addons/junsion_challeng/qrcode/val_'.$mid;
				unlink($path);
			}
			if ($cfg['msgid']){
				$post = array(
						'keyword1' => array(
								'value' => $title,
						),
						'keyword2' => array(
								'value' => $gift['title'],
						),
						'keyword3' => array(
								'value' =>date('Y-m-d H:i:s'),
						),
				);
				$form = get("select id,formid from ".tb("form")." where mid='{$mid}' order by id limit 1");
				$this->sendTemplateProgramMsg($openid,$cfg['msgid'] , $post, $form['formid'], 'challeng/pages/gift/gift');
				del('form',array('id'=>$form['id']));
			}
			
			pdo_query('update '.tablename($this->modulename."_mem")." set reward_num = reward_num+1,reward_price=reward_price+'{$gift['price']}' where id='{$mem['id']}'");
			$arr = array(
					'code' => 1,
					'id' => $newid
			);
			die(json_encode($arr));
		}
		else{
			$arr = array(
					'code' => 0,
					'msg' => '更新中奖记录失败，请联系管理员'
			);
			die(json_encode($arr));
		}
	}
	//支付奖品
	public function doPagePayReward(){
		global $_GPC, $_W;
		echo $this->sitefunc('PayReward');
	}
	
	/**
	 * 分享到群聊恢复答题
	 */
	public function doPageReAnswer(){
		global $_GPC, $_W;
		$_W['uniacid'] = $_W['weid'];
		$openid = $_GPC['mid'];
		//解密群id
		include_once "wxBizDataCrypt.php";
		$appid = $_W['account']['key'];
		$s = pdo_fetch('select session_key from ' . tablename($this->modulename.'_session') . " where openid = '{$openid}'");
		$sessionKey = $s['session_key'];
		$encryptedData = $_GPC['encryptedData'];
		$iv = $_GPC['iv'];
		$pc = new WXBizDataCrypt($appid, $sessionKey);
		$errCode = $pc->decryptData($encryptedData, $iv, $data );
		if($errCode!=0){
			die(json_encode(array('code'=>0,'msg'=>'错误编码：'.$errCode)));
		}
		$qun_info = json_decode($data,true);
		$openGId = $qun_info['openGId'];
		
		$mem = $this->getMem($openid);
		//是否已经分享过该群
		$save = pdo_fetch('select id from ' . tablename($this->modulename.'_nums') . " where mid = '{$mem['id']}' and type=4 and identity = '{$openGId}' ");
		if(!empty($save)) {
			$arr = array(
					'code' => 1,
					'msg' => '您已经分享过该群了'
			);
			die(json_encode($arr));
		}
		insert('nums',array('mid'=>$mem['id'],'type'=>4,'createtime'=>TIMESTAMP,'identity'=>$openGId));
		$arr = array(
				'code' => 2,
				'msg' => '分享成功，恢复答题状态'
		);
		die(json_encode($arr));
	}
	
	/**
	 * 分享到群聊增加次数
	 */
	public function doPageAddNums(){
		global $_GPC, $_W;
		$_W['uniacid'] = $_W['weid'];
		$openid = $_GPC['mid'];
		//解密群id
		include_once "wxBizDataCrypt.php";
		$appid = $_W['account']['key'];
		$s = pdo_fetch('select session_key from ' . tablename($this->modulename.'_session') . " where openid = '{$openid}'");
		$sessionKey = $s['session_key'];
		$encryptedData = $_GPC['encryptedData'];
		$iv = $_GPC['iv'];
		$pc = new WXBizDataCrypt($appid, $sessionKey);
		$errCode = $pc->decryptData($encryptedData, $iv, $data );
		if($errCode!=0){
			die(json_encode(array('code'=>0,'msg'=>'错误编码：'.$errCode)));
		}
		$qun_info = json_decode($data,true);
		$openGId = $qun_info['openGId'];
		$cfg = $this->module['config'];
		if(empty($_GPC['mid']) || empty($openGId))  die(json_encode(array('code'=>0)));
		//分享次数是否已达上线
		if (empty($cfg['get_share_num'])) die(json_encode(array('code'=>0)));
		$mem = $this->getMem($openid);
		//是否已经分享过
		$save = pdo_fetch('select id from ' . tablename($this->modulename.'_nums') . " where mid = '{$mem['id']}' and type=0 and identity = '{$openGId}' ");
		if(!empty($save)) die(json_encode(array('code'=>0)));
	
		if ($cfg['share_num'] > 0){//有上限
			$nums = col('select count(1) from ' . tb('nums') . " where mid = '{$mem['id']}' and type=0 and to_days(from_unixtime(createtime)) = to_days(now())");
			if($cfg['share_num'] <= $nums) die(json_encode(array('code'=>0,'msg'=>$nums)));
		}
		insert('nums',array('mid'=>$mem['id'],'type'=>0,'createtime'=>TIMESTAMP,'identity'=>$openGId));
		pdo_query("update ".tb('mem')." set challeng_num=challeng_num+{$cfg['get_share_num']} where id='{$mem['id']}'");
		$arr = array(
				'code' => 1,
				'num' => $cfg['get_share_num']
				//'num' => $mem['challeng_num']+$cfg['get_share_num']
		);
		die(json_encode($arr));
	}
	
	public function  doPageUpdateNum(){
		global $_GPC, $_W;
		$_W['uniacid'] = $_W['weid'];
		$openid = $_GPC['openid'];
		$num = $_GPC['num'];
		$game = $_GPC['game'];
		$mem = $this->getMem($openid);
		$this->updateFriendsRank($mem['id'], $num, $game);
		die('1');
	}
	
	public function updateFriendsRank($mid,$num,$game=0){
		global $_W;
		$is_share = get('select weid,num from ' . tb('friends') . " where mid = '{$mid}' and type = '{$game}'");
		if(!empty($is_share) && $is_share['num']< $num){
			update('friends',array('num'=>$num),array('mid'=>$mid,'type'=>$game));
		}
	}
	
	public function doPageAddGNums(){
		global $_GPC, $_W;
		$id = $_GPC['id'];
		pdo_query("update ".tb('games')." set num=num+1 where id='{$id}'");
		die('1');
	}
	
	public function doPageGame(){
		global $_GPC, $_W;
		$_W['uniacid'] = $_W['weid'];
		$pagesize = 8;
		$pageindex = max(1, intval($_GPC['page']));
		$limit = "limit " . (($pageindex -1) * $pagesize).','. $pagesize;
		
		$games = getall('select id,title,thumb,des,dummy_num,num,url,appid from ' . tb('games') . " where weid = '{$_W['uniacid']}' and status = 1 order by sort desc {$limit} ");
		if(!empty($games)){
			foreach ($games as $k => $v){
				$games[$k]['thumb'] = toimage($v['thumb']);
				$games[$k]['num'] = $v['dummy_num'] + $v['num'];
				if(empty($v['appid']) && !strstr($v['url'], 'http')){
					$games[$k]['url'] = str_replace('challeng/pages', '..', $v['url']);
				}
			}
		}
		if($_GPC['scroll']){
			if(!empty($games)){
				$data = array(
						'status' => '1',
						'games' => $games,
				);
			}else{
				$data = array('status'=>'0');
			}
			die(json_encode($data));
		}
		$cfg = $this->module['config'];
		$arr = array(
				'games' => $games,
				'rarrow' => toimage($cfg['face']['rarrow']),
				'liulan' => toimage($cfg['face']['liulan']),
		);
		die(json_encode($arr));
	}	
	
	public function doPageIndex(){
		global $_GPC, $_W;
		$_W['uniacid'] = $_W['weid'];
		$cfg = $this->module['config'];
		$openid = $_GPC['openid'];
		$mem = $this->getMem($openid,$_GPC['nickname'],$_GPC['avatar']);
		$challeng_num = $mem['challeng_num'];//会员剩余挑战次数
		$game = empty($_GPC['game'])?0:$_GPC['game'];
		if(!empty($mem)){
			//给会员增加访问次数
			$initnum = get('select id from ' . tb('nums') . " where mid = '{$mem['id']}' and type=3 and to_days(from_unixtime(createtime)) = to_days(now()) limit 1");
			if(empty($initnum['id'])){
				pdo_query('update '.tablename($this->modulename."_mem")." set challeng_num = '{$cfg['base']['initnum']}' where id='{$mem['id']}'");
				insert('nums',array('mid'=>$mem['id'],'type'=>3,'createtime'=>TIMESTAMP));
				$challeng_num = $cfg['base']['initnum'];
			}
		}
		//好友点击增加次数
		$scene = trim($_GPC['scene']);
		if(empty($scene)){
			$shareid = intval($_GPC['shareid']);
		}
		else{
			//获取二维码中的会员id
			$scene = explode(":", $scene);
			$shareid = intval($scene[1]);
		}
		
		if(!empty($shareid) && $mem['id']!=$shareid){
			if($cfg['get_click_num']>0){
				$clicknum = get('select id from ' . tb('nums') . " where mid = '{$shareid}' and type=1 and identity='{$mem['id']}' and to_days(from_unixtime(createtime)) = to_days(now())");
				if(empty($clicknum['id'])){
					if($cfg['click_num']>0){//是否已超出限制
						$nums = col('select count(1) from ' . tb('nums') . " where mid = '{$shareid}' and type=1 and to_days(from_unixtime(createtime)) = to_days(now())");
						if($cfg['click_num'] > $nums) {
							pdo_query('update '.tablename($this->modulename."_mem")." set challeng_num = challeng_num + '{$cfg['get_click_num']}' where id='{$shareid}'");
							insert('nums',array('mid'=>$shareid,'type'=>1,'createtime'=>TIMESTAMP,'identity'=>$mem['id']));
						}
					}
				}
			}
			$is_share = get('select weid from ' . tb('friends') . " where mid = '{$mem['id']}' and shareid = '{$shareid}' and type = '{$game}'");
			if(empty($is_share)){
				$share_data = array(
						'weid' => $_W['uniacid'],
						'mid' => $mem['id'],
						'shareid' => $shareid,
						'type' => $game,
				);
				insert('friends',$share_data);
			}
		}
		//获取所有会员的总参与次数
		$join_num = col('select sum(join_num) from ' . tb('mem') . " where weid = '{$_W['uniacid']}' ");
		//获取智力排行榜
		$best_mems = getall('select id,nickname,avatar,reward_num,reward_price from ' . tb('mem') . " where weid = '{$_W['uniacid']}' and reward_num>0 order by reward_num desc limit {$cfg['base']['rank']} ");
		//获取毅力排行榜
		$will_mems = getall('select id,nickname,avatar,join_num from ' . tb('mem') . " where weid = '{$_W['uniacid']}' and join_num>0 order by join_num desc limit {$cfg['base']['guts']} ");
		//增加挑战次数的价格设置
		$price = $cfg['price'];
		//群内智力
		$group_mems = getall('select mid,num from ' . tb('friends') . " where shareid = '{$mem['id']}' and type='{$game}' and weid = '{$_W['uniacid']}' and num >0 order by num desc,mid desc limit 5"); 
		if(!empty($group_mems)){
			foreach ($group_mems as $k => $v){
				$mids[] = $v['mid']; 
			}
			$share_mems = getall('select id,nickname,avatar from ' . tb('mem') . " where id in (" .implode(',', $mids). ") ",'id');
			foreach ($group_mems as $k => $v){
				$group_mems[$k]['nickname'] = $share_mems[$v['mid']]['nickname'];
				$group_mems[$k]['avatar'] = $share_mems[$v['mid']]['avatar'];
			}
		}
		
		$face = $cfg['face'];
		if(!empty($face)){
			foreach ($face as $k => $v){
				if(!empty($v)) $face[$k] = toimage($v);
			}
		}
		$showLibao = 1;
		if(!empty($mem['new']) && $cfg['appversion']!=$_GPC['v']){
	//		$showLibao = 0;
		}
		if(!empty($cfg['home_adv'])){
			$adv = $cfg['home_adv'];
			foreach ($adv as $k => $v){
				if(!empty($v['pic'])){
					$adv[$k]['pic'] = toimage($v['pic']);
				}
			}
		}
		
		//游戏排序
		$sort = $cfg['sort'];
		$temp = array();
		foreach ($cfg['game_status'] as $k => $v){
			if($v==1) {
				$k = str_replace('game', '', $k);
				$temp[$k] = $sort[$k];
			}
		}
		$sort_temp = array();
		foreach ($temp as $k => $v){
			if(empty($v)) $v = 0;
			$sort1[] = array(
					'gtype' => $k,
					'sort' => $v
			);
			$sort_temp[] = $v;
		}
		array_multisort($sort_temp,SORT_DESC,$sort1);
		$sort = array();
		foreach ($sort1 as $ks => $vs){
			$sort[] = $vs['gtype'];
		}
		$arr = array(
				'join_num' => $join_num,
				'best_mems' => $best_mems,
				'will_mems' => $will_mems,
				'group_mems' => $group_mems,
				'price' => $price,
				'challeng_num' => $challeng_num,
				'title' =>$cfg['base']['title'],
				'initnum' =>$cfg['base']['initnum'],
				'get_share_num' =>$cfg['get_share_num'],
				'share_num' =>$cfg['share_num'],
				'guts' => $cfg['base']['guts'],
				'express_fee' => $cfg['base']['express_fee'],
				'mid' => $mem['id'],
				'face' => $face,
				'libao' => $showLibao,
				'font' => $cfg['font'],
				'adv' => $adv,
				'sort' => $sort,
		);
		if ($cfg['msg']['txt']) $arr['msg'] = $cfg['msg'];
		if(empty($mem['unionid'])){
			$arr['getUnionid'] = 1;
		}
		if ($game >= 6 && !isGameHost($game)) $game = 0;
		$g_num = $game>0?$game:'';
		$game_info = $cfg['game'.$g_num];
		if(!empty($game_info['logo'])) $game_info['logo'] = toimage($game_info['logo']);
		$arr['game'] = $game_info;
		//删除游戏记录文件
		$path = IA_ROOT.'/addons/junsion_challeng/qrcode/val_'.$mem['id'];
		if(file_exists($path)){
			unlink(IA_ROOT.'/addons/junsion_challeng/qrcode/val_'.$mem['id']);
		}
		$path = IA_ROOT.'/addons/junsion_challeng/qrcode/play_'.$mem['id'];
		if(file_exists($path)){
			unlink(IA_ROOT.'/addons/junsion_challeng/qrcode/play_'.$mem['id']);
		}
		if ($cfg['clipboard']) $arr['clipboard'] = $cfg['clipboard'];
		die(json_encode($arr));
	}
	
	public function doPageGetAgreement(){
		global $_GPC, $_W;
		$_W['uniacid'] = $_W['weid'];
		$cfg = $this->module['config'];
		$agreement = $cfg['agreement'];
		$arr = array(
				'agreement' => $agreement,
		);
		die(json_encode($arr));
	}
	
	public function doPageTzFail(){
		global $_GPC, $_W;
		$_W['uniacid'] = $_W['weid'];
		$openid = $_GPC['openid'];
		$mem = $this->getMem($openid);
		
		$cfg = $this->module['config'];
		$price = $cfg['price'];
		
		
		$arr = array(
				'express_fee' =>$cfg['base']['express_fee'],
				'get_share_num' =>$cfg['get_share_num'],
				'express_fee' =>$cfg['base']['express_fee'],
				'share_num' =>$cfg['share_num'],
				'price' => $price,
				'mem' => $mem
		);
		die(json_encode($arr));
	}
	
	public function doPageUser(){
		global $_GPC, $_W;
		$_W['uniacid'] = $_W['weid'];
		$openid = $_GPC['openid'];
		$mem = pdo_fetch('select id,nickname,avatar,challeng_num,join_num,reward_num from ' . tablename($this->modulename.'_mem') . " where propenid = '{$openid}' and weid='{$_W['uniacid']}'");
		
		$cfg = $this->module['config'];
		//增加挑战次数的价格设置
		$price = $cfg['price'];
		$poster = unserialize($cfg['poster']);
		$face = $cfg['face'];
		if(!empty($face['custom'])){
			$face['custom'] = toimage($face['custom']);
		}
		$adv = $cfg['adv'];
		if(!empty($adv)){
			foreach ($adv as $k => $v){
				if(!empty($v['pic'])) $adv[$k]['pic'] = toimage($v['pic']);
				if(empty($v['appid']) && !strstr($v['link'], 'http')){
					$adv[$k]['link'] = str_replace('challeng/pages', '..', $v['link']);
				}
			}
		}
		$arr = array(
				'mem' => $mem,
				'price' => $price,
				'get_share_num' =>$cfg['get_share_num'],
				'share_num' =>$cfg['share_num'],
				'user_tip' =>$cfg['font']['user_tip'],
				'more_tz' =>$cfg['font']['more_tz'],
				'poster_switch' => $poster['switch'],
				'poster_tips' => $poster['tips'],
				'custom' => $face['custom'],
				'share2' => toimage($face['share2']),
				'u_bg' => toimage($face['u_bg']),
				'adv' => $adv,
		);
		die(json_encode($arr));
	}

	public function doPageGroupMem(){
		global $_GPC, $_W;
		$_W['uniacid'] = $_W['weid'];
		$mid = $_GPC['mid'];
		$pagesize = 5;
		$pageindex = max(1, intval($_GPC['page']));
		$game = empty($_GPC['game'])?0:$_GPC['game'];
		$group_mems = getall('select mid,num from ' . tb('friends') . " where shareid = '{$mid}' and type='{$game}' and weid = '{$_W['uniacid']}' order by num desc,mid desc limit " . ($pageindex - 1) * $pagesize ."," . $pagesize);
		if(!empty($group_mems)){
			foreach ($group_mems as $k => $v){
				$mids[] = $v['mid'];
			}
			$share_mems = getall('select id,nickname,avatar from ' . tb('mem') . " where id in (" .implode(',', $mids). ") ",'id');
			foreach ($group_mems as $k => $v){
				$group_mems[$k]['nickname'] = $share_mems[$v['mid']]['nickname'];
				$group_mems[$k]['avatar'] = $share_mems[$v['mid']]['avatar'];
			}
		}
		if(!empty($group_mems)){
			$data = array(
					'status' => '1',
					'group_mems' => $group_mems,
			);
		}
		else{
			$data = array('status'=>'0');
		}
		die(json_encode($data));
	}
	
	public function doPageWillMem(){
		global $_GPC, $_W;
		$_W['uniacid'] = $_W['weid'];
		$cfg = $this->module['config'];
		$pagesize = $cfg['base']['guts'];
		$pageindex = max(1, intval($_GPC['page']));
		//获取毅力排行榜
		$will_mems = getall('select id,nickname,avatar,join_num from ' . tb('mem') . " where weid = '{$_W['uniacid']}' and join_num>0 order by join_num desc limit " . ($pageindex - 1) * $pagesize ."," . $pagesize);
		if(!empty($will_mems)){
			$data = array(
					'status' => '1',
					'will_mems' => $will_mems,
			);
		}
		else{
			$data = array('status'=>'0');
		}
		die(json_encode($data));
	}
	
	public function doPageMyGift(){
		global $_GPC, $_W;
		$_W['uniacid'] = $_W['weid'];
		$openid = $_GPC['openid'];
		$mem = $this->getMem($openid);
		$pagesize = 5;
		$pageindex = max(1, intval($_GPC['page']));
		$limit = "limit " . (($pageindex -1) * $pagesize).','. $pagesize;
		$list = pdo_fetchall('select id,orderno,price,createtime,status,gid from ' . tablename($this->modulename.'_reward') . " where weid = '{$_W['uniacid']}' and mid='{$mem['id']}' order by id desc {$limit}");
		if(!empty($list)){
			$cfg = $this->module['config'];
			$face = $cfg['face'];
			foreach ($list as $k => $v){
				$gids[] = $v['gid'];
			}
			$gids = array_unique($gids);
			$gifts = pdo_fetchall('select id,title,logo from ' . tablename($this->modulename.'_gift') . " where weid = '{$_W['uniacid']}' and id in ( " . implode(',', $gids) . " )",array(),'id');
			foreach ($list as $k => $v){
				if(!empty($gifts[$v['gid']]['logo']))
					$list[$k]['logo'] = toimage($gifts[$v['gid']]['logo']);
				else{
					if(!empty($face['reward'])){
						$list[$k]['logo'] = toimage($face['reward']);
					}
				}
				if(!empty($gifts[$v['gid']]['title'])) $list[$k]['title'] = $gifts[$v['gid']]['title'];
				if($v['status']== 1) $list[$k]['title'] = '待工作人员分配';
				$list[$k]['createtime'] = date('Y-m-d H:i',$v['createtime']);
			}
		}
		if($_GPC['scroll']){
			if(!empty($list)){
				$data = array(
						'status' => '1',
						'list' => $list,
				);
			}else{
				$data = array('status'=>'0');
			}
			die(json_encode($data));
		}
		die(json_encode(array('code'=>1,'mid'=>$mem['id'],'list'=>$list)));
	}
	
	public function doPageGift(){
		global $_GPC, $_W;
		$_W['uniacid'] = $_W['weid'];
		$pagesize = 5;
		$pageindex = max(1, intval($_GPC['page']));
		//礼品库
		$gifts = getall('select id,title,logo from ' . tb('gift') . " where weid = '{$_W['uniacid']}' order by sort desc limit " . ($pageindex - 1) * $pagesize ."," . $pagesize);
		if(!empty($gifts)){
			foreach ($gifts as $k => $v){
				$gifts[$k]['logo'] = toimage($v['logo']);
			}
		}
		if($_GPC['scroll']){
			if(!empty($gifts)){
				$data = array(
						'status' => '1',
						'gifts' => $gifts,
				);
			}else{
				$data = array('status'=>'0');
			}
			die(json_encode($data));
		}
		die(json_encode(array('code'=>1,'gifts'=>$gifts)));
	}
	
	public function doPageFID(){
		global $_GPC, $_W;
		$mem = $this->getMem($_GPC['openid']);
		if (empty($mem['id'])) return ;
		$formid = trim($_GPC['formId']);
		//删除7天前的
		$time = time() - 7 * 24 * 3600;
		pdo_query('delete from '.tablename($this->modulename.'_form')." where mid='{$mem['id']}' and createtime <= {$time}");
		$form = get("select id,formid from ".tb("form")." where mid='{$mem['id']}' order by id limit 1");
		if(empty($form)){
			pdo_insert($this->modulename.'_form',array('mid'=>$mem['id'],'formid'=>$formid,'createtime'=>time()));
		}
		else{
			pdo_update($this->modulename.'_form',array('formid'=>$formid,'createtime'=>time()),array('id'=>$form['id']));
		}		
	}
	
	public function sendTemplateProgramMsg($openid,$msgid,$data,$form_id,$url,$topcolor = '#FF0000'){
		global $_W;
		$token = $this->getAccessToken();
		$post_url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='.$token;
		load()->func('communication');
		$post_data = json_encode(array(
				'touser' => $openid,
				'template_id' => $msgid,
				'page' => $url,
				'form_id' => $form_id,
				'data' => $data,
				'color' => $topcolor
		));
		$json = ihttp_post($post_url,$post_data);
		file_put_contents(IA_ROOT."/addons/junsion_challeng/rmsg", json_encode($post_data)."\n".$json['content']."\n");
		return json_decode($json['content'],true);
	}
	
	public function doPageShare(){
		global $_GPC, $_W;
		$cfg = $this->module['config'];
		$path = 'challeng/pages/index/index';
		$gtype = empty($_GPC['gtype'])?0:$_GPC['gtype'];
		if($gtype==1) $share = $cfg['share1'];
		else if($gtype==2) $share = $cfg['share2'];
		else if($gtype==3) $share = $cfg['share3'];
		else if($gtype==4) $share = $cfg['share4'];
		else if($gtype==5) $share = $cfg['share5'];
		else if($gtype==6) $share = $cfg['share6'];
		else if($gtype==7) $share = $cfg['share7'];
		else if($gtype==8) $share = $cfg['share8'];
		else if($gtype==9) $share = $cfg['share9'];
		else $share = $cfg['share0'];
		$openid = $_GPC['openid'];
		$mem = $this->getMem($openid);
		$share['title'] = str_replace('#nickname#', $mem['nickname'], $share['title']);
		if(!empty($share['pic'])) $share['pic'] = toimage($share['pic']);
		die(json_encode(array('title'=>$share['title'],'pic'=>$share['pic'],'path'=>$path))); 
	}
	
	public function doPageSysinfo(){
		global $_GPC, $_W;
		$cfg = $this->module['config'];
		$check_status = 0;
		if ($cfg['appversion'] == $_GPC['v']){
			$check_status=1;
		}
		else{
			$footer = pdo_fetchall('select id,title,color,thumb,url from ' . tablename($this->modulename.'_footer') . " where weid = '{$_W['uniacid']}' order by displayorder desc");
		}
		if(!empty($footer)){
			foreach ($footer as $k => $v){
				$footer[$k]['thumb'] = toimage($v['thumb']);
			}
		}
		$music = array();
		if($_GPC['music']==1){
			$music['err_music'] = empty($cfg['err_music'])?'':tomedia($cfg['err_music']);
			$music['music'] = empty($cfg['music'])?'':tomedia($cfg['music']);
			$music['time'] = TIMESTAMP * 1000;
		}
		$sort = $cfg['sort'];
		$sort1 = array();
		$gnum = 0;
		foreach ($cfg['game_status'] as $k => $v){
			if($v==1) {
				$k = str_replace('game', '', $k);
				$sort1[$k] = $sort[$k];
				$gnum++;
			}
		}
		$max_sort = max($sort1);
		$game = 0;
		foreach ($cfg['sort'] as $k => $v){
			if($max_sort==$v){
				$game=$k;
				break;
			}
		}
		if ($cfg['appversion'] == $_GPC['v']){
			$game = $cfg['check_game'];
		}
		//下次更新删除
		$game_status = array();
		foreach ($cfg['game_status'] as $k => $v){
			if($v==1) $game_status[] = 1;
			else $game_status[] = 0;
		}
		$data = array('footer'=>$footer,'color'=>$cfg['wx_color'],'check_status'=>$check_status,'game_status'=>$game_status,'game'=>$game,'gnum'=>$gnum,'music'=>$music);		
		if ($cfg['advs'] && $cfg['appversion'] != $_GPC['v']){
			$data['advs'] = explode("\r\n", $cfg['advs']);
		}
		die(json_encode($data));
	}
	
	public function doPageInfo(){
		global $_GPC, $_W;
		$this->getMem($_GPC['openid'],$_GPC['nickname'],$_GPC['avatar']);
	}

	function sitefunc($action){
		global $_W;
		$_W['uniacid'] = $_W['weid'];
		$site = WeUtility::createModuleSite('junsion_challeng');
		$method = 'doMobile'.$action;
		return $site->$method();
	}
	
	public function doPageBlackMem(){
		global $_GPC, $_W;
		$openid = $_GPC['openid'];
		if(empty($openid) || strlen($openid) != 28){
			die('0');
		}
		update('mem',array('status'=>1),array('propenid'=>$openid));
		die('1');
	}
	public function doPageIsMem(){
		global $_GPC, $_W;
		$openid = $_GPC['openid'];
		if(empty($openid) || strlen($openid) != 28){
			die('0');
		}
		echo col('select status from '.tb('mem')." where propenid='{$openid}'");
	}
	
	private function getMem($openid,$nickname = '',$avatar = ''){
		global $_W;
		$_W['uniacid'] = $_W['weid'];
		if(empty($openid)){
			return '';
		}
		if (!pdo_fieldexists('junsion_challeng_mem', 'gametoken')) {
			pdo_query("ALTER TABLE " . tablename('junsion_challeng_mem') . " ADD  `gametoken` varchar(50) DEFAULT '' COMMENT '';");
		}
		$mem = pdo_fetch('select id,status,propenid,unionid,challeng_num,nickname,avatar,gametoken from ' . tablename($this->modulename.'_mem') . " where propenid = '{$openid}' and weid='{$_W['uniacid']}'");
		if(empty($mem) && strlen($openid)==28){
			$data = array(
					'weid' => $_W['uniacid'],
					'propenid' => $openid,
					'nickname' => $nickname,
					'avatar' => $avatar,
					'createtime' => TIMESTAMP
			);
			pdo_insert($this->modulename.'_mem',$data);
			$mem['id'] = pdo_insertid();
			$mem['new'] = 1;
		}else{
			if(!empty($avatar) && empty($mem['avatar'])){
				pdo_update($this->modulename.'_mem',array('nickname' => $nickname,'avatar' => $avatar),array('id'=>$mem['id']));
			}
		}
		return $mem;
	}
	
	public function doPagePoster(){
		global $_W,$_GPC;
		$_W['uniacid'] = $_W['weid'];
		$openid = $_GPC['openid'];
		$mem = $this->getMem($openid);
		if($mem['status']==1){
			$arr = array(
					'code' => 0,
					'msg' => '您已被拉入黑名单，无法生成海报'
			);
			die(json_encode($arr));
		}
		$cfg = $this->module['config'];
		$poster = unserialize($cfg['poster']);
		if(empty($poster)){
			$arr = array(
					'code' => 0,
					'msg' => '海报信息不存在'
			);
			die(json_encode($arr));
		}
		if(empty($poster['switch'])){
			$arr = array(
					'code' => 0,
					'msg' => '系统未开启海报设置'
			);
			die(json_encode($arr));
		}
		$POSTER_PATH = IA_ROOT."/addons/junsion_challeng/qrcode/";
		if(!file_exists($POSTER_PATH)){
			mkdir($POSTER_PATH,'777');
		}
		$POSTER_PATH .= "qrcode_#id#.png";
		$data = $poster['data'];
		$qrcode = str_replace('#id#', $mem['id'], $POSTER_PATH);
		if(file_exists($qrcode)){
			$arr = array(
					'code'=>1,
					'tips'=>$poster['tips'],
					'img'=>str_replace(IA_ROOT.'/', $_W['siteroot'], $qrcode)."?t=".time()
					
			);
			die(json_encode($arr));
		}
		set_time_limit(0);
		@ini_set('memory_limit', '256M');
		$bg = $poster['bg'];
		$size = getimagesize(tomedia($bg));
		$target = imagecreatetruecolor($size[0], $size[1]);
		$bg = $this->imagecreates(tomedia($bg));
		imagecopy($target, $bg, 0, 0, 0, 0,$size[0], $size[1]);
		imagedestroy($bg);
		foreach ($data as $value) {
			$value = $this->trimPx($value);
			if ($value['type'] == 'qr'){
				$img = $this->getQrcodeData($mem['id']);
				$this->mergeImage($target,@imagecreatefromstring($img),array('left'=>$value['left'],'top'=>$value['top'],'width'=>$value['width'],'height'=>$value['height']),1);
				//$this->mergeImage($target,$img,array('left'=>$value['left'],'top'=>$value['top'],'width'=>$value['width'],'height'=>$value['height']),1);
			}elseif ($value['type'] == 'img'){
				$img = $this->saveImage($mem['avatar'],random(32));
				$this->mergeImage($target,$img,array('left'=>$value['left'],'top'=>$value['top'],'width'=>$value['width'],'height'=>$value['height']));
				@unlink($img);
			}elseif ($value['type'] == 'name') $this->mergeText($target,$mem['nickname'],array('size'=>$value['size'],'color'=>$value['color'],'left'=>$value['left'],'top'=>$value['top']));
		}
		imagejpeg($target, $qrcode);
		imagedestroy($target);
		$qrcode = str_replace(IA_ROOT.'/', $_W['siteroot'], $qrcode);
		
		$arr = array(
				'code'=>1,
				'img'=>$qrcode."?t=".time(),
				'tips'=>$poster['tips'],
		);
		die(json_encode($arr));
	}
	
	public function getQrcodeData($mid){
		global $_W;
		$_W['uniacid'] = $_W['weid'];
		if(empty($mid)) return '';
		$path = IA_ROOT."/addons/junsion_challeng/qrcode";
		if(!file_exists($path)){
			mkdir($path,'777');
		}
		$path = $path.'/'.$mid.'.png';
		if(file_exists($path)) return $path;
	
		$url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=".$this->getAccessToken();
		$params = array();
		$params['scene'] = $this->modulename.':'.$mid;
		$params['page'] = "challeng/pages/index/index";
		load()->func('communication');
		$result = ihttp_post($url, json_encode($params));
		$res = json_decode($result['content'],true);
		if ($res['errcode']) return '生成错误：'.$result['content'];
		return $result['content'];
		//输出为图片
		$output = imagecreatefromstring($result['content']);
		imagejpeg($output, $path, 80);
		return $path;
	}
	
	function trimPx($data) {
		$data['left'] = intval(str_replace('px', '', $data['left'])) * 2;
		$data['top'] = intval(str_replace('px', '', $data['top'])) * 2;
		$data['width'] = intval(str_replace('px', '', $data['width'])) * 2;
		$data['height'] = intval(str_replace('px', '', $data['height'])) * 2;
		$data['size'] = intval(str_replace('px', '', $data['size'])) * 2;
		$data['src'] = tomedia($data['src']);
		return $data;
	}
	function imagecreates($bg) {
		$bgImg = @imagecreatefrompng($bg);
		if (FALSE == $bgImg) {
			$bgImg = @imagecreatefromjpeg($bg);
		}
		if (FALSE == $bgImg) {
			$bgImg = @imagecreatefromgif($bg);
		}
		return $bgImg;
	}
	function mergeText($target ,$text , $data) {
		$font = IA_ROOT . '/web/resource/fonts/msyhbd.ttf';
		$colors = $this->hex2rgb($data['color']);
		$color = imagecolorallocate($target, $colors['red'], $colors['green'], $colors['blue']);
		imagettftext($target, $data['size'], 0, $data['left'], $data['top'] + $data['size'], $color, $font, $text);
		return $target;
	}
	function hex2rgb($colour) {
		if ($colour[0] == '#') {
			$colour = substr($colour, 1);
		}
		if (strlen($colour) == 6) {
			list($r, $g, $b) = array($colour[0] . $colour[1], $colour[2] . $colour[3], $colour[4] . $colour[5]);
		} elseif (strlen($colour) == 3) {
			list($r, $g, $b) = array($colour[0] . $colour[0], $colour[1] . $colour[1], $colour[2] . $colour[2]);
		} else {
			return false;
		}
		$r = hexdec($r);
		$g = hexdec($g);
		$b = hexdec($b);
		return array('red' => $r, 'green' => $g, 'blue' => $b);
	}
	function saveImage($url,$tag = '') {
		$ch = curl_init ();
		curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, 'GET' );
		curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, false );
		curl_setopt ( $ch, CURLOPT_URL, $url );
		ob_start ();
		curl_exec ( $ch );
		$return_content = ob_get_contents ();
		ob_end_clean ();
		$return_code = curl_getinfo ( $ch, CURLINFO_HTTP_CODE );
		$filename = IA_ROOT."/addons/junsion_challeng/qrcode/temp{$tag}.jpg";
		$fp= @fopen($filename,"a"); //将文件绑定到流 
		fwrite($fp,$return_content); //写入文件
		return $filename;
	}
	function mergeImage($target, $imgurl , $data,$type = '') {
		if (!$type)
			$img = $this->imagecreates($imgurl);
			else $img = $imgurl;
			$w = imagesx($img);
			$h = imagesy($img);
			imagecopyresized($target, $img, $data['left'], $data['top'], 0, 0, $data['width'], $data['height'], $w, $h);
			imagedestroy($img);
			return $target;
	}
	
	private function getAccessToken() {
		global $_W;
		load()->model('wxapp');
		$acid = $_W['acid'];
		if (empty($acid)) {
			$acid = $_W['uniacid'];
		}
		$account = WeAccount::create($acid);
		$token = $account->getAccessToken();
		return $token;
	}
	
}
